<extend name="public/base2" />
<block name="head">
    <!-- jsGrid -->
    <link rel="stylesheet" type="text/css" href="__ADMINLTE__/plugins/jsgrid/jsgrid.min.css">
    <link rel="stylesheet" type="text/css" href="__ADMINLTE__/plugins/jsgrid/jsgrid-theme.min.css">
    <!-- jQuery UI -->
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css">
    <!-- Sweetalert 2@9 -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@9.10.12/dist/sweetalert2.css">
    <!-- Bootstrap v4 -->
    <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</block>
<block name="main-content">
    <div class="card">
        <!-- .card-header -->
        <div class="card-header">
            <h3 class="card-title">JsGrid Table</h3>
        </div>
        <!-- /.card-header -->
        <!-- .card-body -->
        <div class="card-body">
            <div id="alert-area"></div>
            <div id="jsGrid"></div>
            <div id="detailsDialog">
                <form id="detailsForm">
                    <div class="details-form-field">
                        <label for="parent">父级菜单:</label>
                        <select id="parent" name="parent_id">
                            <option value="0" selected>作为一级菜单</option>
                        </select>
                    </div>
                    <div class="details-form-field">
                        <label for="name">名称:</label>
                        <input id="name" name="name" type="text" />*
                    </div>
                    <div class="details-form-field">
                        <label for="url">控制器/方法:</label>
                        <input id="url" name="url" type="text" />*
                    </div>
                    <div class="details-form-field">
                        <label for="param">参数:</label>
                        <input id="param" name="param" type="text" />
                        <p class="help-block">例如:id=3&p=3</p>
                    </div>
                    <div class="details-form-field">
                        <label for="icon">图标:</label>
                        <input id="icon" name="icon" type="text" />
                        <p class="help-block">
                            <a href="https://fontawesome.com/icons?d=gallery&m=free" target="_blank">选择图标</a>如fa-cogs
                        </p>
                    </div>
                    <div class="details-form-field">
                        <label for="status">状态:</label>
                        <input id="status1" name="status" value="1" type="radio" />
                        <span>显示</span>
                        <input id="status2" name="status" value="0" type="radio" />
                        <span>隐藏</span>
                    </div>
                    <div class="details-form-field">
                        <label for="sort">排序:</label>
                        <input id="sort" name="sort" type="number" />
                    </div>
                </form>
            </div>

        </div>
        <!-- /.card-body -->
        <!-- <div class="card-footer clearfix"></div> -->
    </div>
    <!-- /.card -->
</block>
<!-- /.main-content -->
<block name="footer-script">
    <!-- jQuery -->
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <!-- jQuery UI -->
    <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
    <!-- jQuery validate -->
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>

    <script>window.jQuery || document.write('<script src="__ADMINLTE__/plugins/jquery/jquery.min.js"><\/script>')</script>
    <!-- jsGrid -->
    <script src="__ADMINLTE__/plugins/jsgrid/jsgrid.min.js"></script>
    <script src="__ADMINLTE__/plugins/jsgrid/i18n/jsgrid-zh-cn.js"></script>
    <!-- Bootstrap 4 -->
    <script src="__ADMINLTE__/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- Sweetalert 2@9 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9.10.12/dist/sweetalert2.min.js"></script>
    <!-- AdminLTE App -->
    <script src="__ADMINLTE__/dist/js/adminlte.min.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="__ADMINLTE__/dist/js/demo.js"></script>
    <!-- page script -->
    <script>
        var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
        $.fn.bootstrapBtn = bootstrapButton            // give $().bootstrapBtn the Bootstrap functionality

        $(function () {
            var menus_data = JSON.parse('{$menu_list}');
            /********************START******************
            **********将菜单添加到父级菜单选择框里********/
            var option = '';
            menus_data.forEach(function (value) {
                var indent = '&nbsp;';
                indent = indent.repeat(value.level * 4);
                if (0 != value.level) {
                    indent += '|─';
                }
                option += '<option value="' + value.id + '">' + indent + value.title + '</option>';
            });
            $("#detailsForm #parent").append(option);
            /******************END********************/

            jsGrid.locale("zh-cn");

            $("#jsGrid").jsGrid({
                height: "70%",
                width: "100%",
                editing: true,
                confirmDeleting: false,

                data: menus_data,
                controller: {
                    updateItem: function (item) {
                        var d = $.Deferred();

                        $.ajax({
                            type: "PUT",
                            url: "{:url('edit')}",
                            data: item,
                            dataType: "json"
                        }).done(
                            function (response) {
                                0 == response.code && d.reject(response)
                                1 == response.code && d.resolve(response.data, response)
                            }
                        );

                        return d.promise();
                    },
                    deleteItem: function (item) {
                        $("#jsGrid").jsGrid("option", "loadIndication", false);
                        var d = $.Deferred();
                        Swal.fire({
                            title: "{:lang('ARE_YOU_SURE_DELETE', ['" + item.title + "'])}",
                            icon: 'question',
                            showCancelButton: true,
                            cancelButtonColor: '#d33',
                            showLoaderOnConfirm: true,
                            preConfirm: () => {
                                return fetch("{:url('delete')}", {
                                    method: 'PUT',
                                    body: JSON.stringify(item),
                                    headers: {
                                        'content-type': 'application/json'
                                    },
                                }).then(response => { // 箭头函数
                                    if (response.ok) {
                                        return response.json();
                                    }
                                    throw new Error("{:lang('ABNORMAL_NETWORK_RESPONSE')}");
                                }).catch(error => {
                                    Swal.showValidationMessage(
                                        "{:lang('REQUEST_FAILED', ['" + error.message + "'])}"
                                    )
                                })
                            }
                        }).then((result) => {
                            if (result.value) {
                                var data = JSON.parse(result.value);
                                if (1 == data.code) {
                                    Swal.fire({
                                        icon: 'success',
                                        title: data.msg,
                                        width: 350,
                                        timer: 2000,
                                        showConfirmButton: false
                                    });
                                    d.resolve(data);
                                } else if (0 == data.code) {
                                    $('#alert-area').html(data.msg);
                                    d.reject(data);
                                }

                            }
                        })

                        return d.promise();
                    }
                },

                fields: [
                    {
                        name: "id", title: 'ID', type: "text", width: '5.5%', align: "center",
                        cellRenderer: function (item, itemIndex) {
                            return $("<td>").attr('data-id', itemIndex['id']).text(item);
                        }
                    },
                    {
                        name: "title", title: '菜单名称', type: "text", width: '41%',
                        cellRenderer: function (item, itemIndex) {
                            if (itemIndex['level'] > 0) {
                                item = '|─ ' + item;
                            }
                            return $("<td>").addClass('level-' + itemIndex['level']).text(item);
                        }
                    },
                    { name: "url", title: '控制器/方法', type: "text", width: '30%' },
                    {
                        name: "status", title: '状态', type: "text", width: '7.5%', align: "center",
                        cellRenderer: function (item, itemIndex) {
                            let icon = 'fa-toggle-on';
                            let style = ' text-success';
                            1 != itemIndex['status'] && (icon = 'fa-toggle-off');
                            if (1 != itemIndex['status'])
                            {
                                icon = 'fa-toggle-off';
                                style = ' text-danger';
                            }
                            return $("<td>").html('<i class="fa ' + icon + style + ' fa-2x"></i>');
                        }
                    },
                    {
                        type: "control",
                        width: '10%',
                        headerTemplate: function () {
                            return '操作'
                        }
                    },
                    { name: "sort", title: "{:lang('SORT')}", type: "number", width: '6%', align: "center" },
                ],
                rowClick: function (args) {
                    // console.log(args.item);
                    showDetailsDialog("Edit", "编辑", args.item);
                },
                onItemUpdating: function (args) {
                    window.updatingItemIndex = args.itemIndex;
                },
            });

            $("#detailsDialog").dialog({
                autoOpen: false,
                width: 500,
                close: function () {
                    $("#detailsForm").validate().resetForm();
                    $("#detailsForm").find(".error").removeClass("error");
                },
                buttons: [
                    {
                        text: "保存",
                        icon: "ui-icon-heart",
                        click: function () {
                            $("#detailsForm").submit();
                        }
                    },
                    {
                        text: "取消",
                        icon: "ui-icon-heart",
                        click: function () {
                            $(this).dialog("close");
                        }
                    }
                ]
            });

            $("#detailsForm").validate({
                debug: true,
                rules: {
                    name: "required",
                    url: "required",
                },
                messages: {
                    name: "名称不能为空",
                    url: "控制器/方法不能为空"
                },
                submitHandler: function () {
                    formSubmitHandler();
                }
            });

            var formSubmitHandler = $.noop;

            var showDetailsDialog = function (dialogType, title, client) {
                $("#detailsForm #parent").val(client.pid);
                $("#name").val(client.title);
                $("#url").val(client.url);
                $("#param").val(client.params);
                $("#icon").val(client.icon);
                // 选择“显示”
                $("#status1").prop("checked", 1 == client.status);
                // 选择“隐藏”
                $("#status2").prop("checked", 0 == client.status);
                $("#sort").val(client.sort);

                formSubmitHandler = function () {
                    saveClient(client, dialogType === "Add");
                };

                $("#detailsDialog").dialog("option", "title", title + "菜单").dialog("open");
            };

            var saveClient = function (client, isNew) {
                    // console.log(client);
                $.extend(client, {
                    pid: parseInt($("#parent").val()),
                    title: $("#name").val(),
                    url: $("#url").val(),
                    params: $("#param").val(),
                    icon: $("#icon").val(),
                    status: parseInt($("#detailsForm input[name='status']:checked").val()),
                    sort: parseInt($("#sort").val()),
                });

                // console.log(client);
                $("#jsGrid").jsGrid(isNew ? "insertItem" : "updateItem", client).done(
                    function (response, response2) {
                        var indent = '&nbsp;';
                        indent = indent.repeat(response.level * 4);
                        if (response.level > 0) {
                            indent += '|─';
                        }
                        // 更新对话框里的选择项
                        $("#detailsForm #parent option[value='" + response.id + "']").html(indent + response.title);
                        // 如果有警告信息，删之
                        if ($('#alert-area').children().length > 0) {
                            $('#alert-area').html('');
                        }
                        Swal.fire({
                            icon: 'success',
                            title: response2.msg,
                            width: 350,
                            timer: 1500,
                            showConfirmButton: false
                        });
                    }
                ).fail(
                    function (response) {
                        // 响应错误信息，则将menus_data里更新项重置
                        menus_data.splice(updatingItemIndex, 1, response.data)
                        $("#jsGrid").jsGrid("option", "data", menus_data)
                        $('#alert-area').html(response.msg);
                    }
                );

                $("#detailsDialog").dialog("close");
            };
        });
    </script>
</block>